package practice;

/**
 * @Auther Jun jie Yi
 * @Date 16:08 2022/1/13
 */
public class LeetCode8 {
    public static void main(String[] args) {
        System.out.println(myAtoi1("0000000-12aa"));
//        System.out.println(Integer.MIN_VALUE);
    }

    public static int myAtoi(String s) {
        int len = s.length();
        int i = 0, j = 0, space = 0, symbol = 0;//space为中间空格标记，symbol为符号标记
        int[] t = new int[12];
        //0 代表 +，1代表 -
        t[j++] = 0;
        while (i < len) {
            char r = s.charAt(i);
            if (r == ' ' && space == 0) {
                i++;
                continue;
            }
            //只取数字
            if (((byte) r) >= 48 && ((byte) r) <= 57) {
                space = 1;
                symbol = 1;
                int e = (byte) r - 48;
                if (e != 0) {
                    t[j++] = e;
                } else if (t[1] != 0) {
                    t[j++] = e;
                }
                //数组越界数字必超 int 界限
                if (j == 12) {
                    break;
                }
            } else if (r == '-' && symbol == 0) {
                space = 1;
                symbol = 1;
                t[0] = 1;
            } else if (r == '+' && symbol == 0) {
                space = 1;
                symbol = 1;
                t[0] = 0;
            } else {
                break;
            }
            i++;
        }
        long re = 0, m = 1;
        for (int k = j - 1; k > 0; k--) {
            re = re + t[k] * m;
            m = 10 * m;
        }
        if (t[0] == 1) {
            if (-re < Integer.MIN_VALUE) {
                return Integer.MIN_VALUE;
            }
            return (int) -re;
        } else if (re > Integer.MAX_VALUE) {
            return Integer.MAX_VALUE;
        } else {
            return (int) re;
        }
    }

    public static int myAtoi1(String s) {
        int n = s.length();
        int index = 0;
        // 去除前导空格
        while (index < n && s.charAt(index) == ' ') {
            index++;
        }
        // 如果是极端情况，全为空格
        if (index == n) {
            return 0;
        }
        // 判断正负号
        int sign = 1;
        char firstChar = s.charAt(index);
        if (firstChar == '+') {
            index++;
        } else if (firstChar == '-') {
            index++;
            sign = -1;
        }
        // 遍历后续，初始化答案为0
        int res = 0;
        while (index < n) {
            // 非数字，跳出，返回答案
            if (s.charAt(index) < '0' || s.charAt(index) > '9') {
                break;
            }
            int num = s.charAt(index) - '0';
            // 判断是否溢出
            int cur = res * 10 + sign * num;
            // 如果溢出，返回32位整数的最大值或最小值
            if (cur / 10 != res) {
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            // 如果没有溢出，那就把cur赋值给答案
            res = cur;
            index++;
        }
        return res;

    }
}
